/**
 * @desc tab分页
 * */
define(['jquery', 'classer', 'ajaxer', 'eventer', 'objecter'], function($, classer, ajaxer, eventer, objecter){
	var tabs = {
		build : function(options){
			var me = this;
            $(options.el).each(function(){
                var opts = objecter.extend({}, options, {el : this});
            	new Taber(opts);
            });
		}
	},

	Taber = classer.extend({
		init : function(options){
			this.setOptions(objecter.extend({}, Taber.defaults, options));
			options = this.getOptions();

			var me = this,
				$this = $(options.el),
				tabCls = options.tabCls,
				activeCls = options.activeCls,
				$tabList = $this.find('.' + tabCls),
				$activeTab;
			$tabList.each(function(){
				var $this = $(this);
				$this.on(eventer.events.down, function(){
					me.active($(this));
				});
				if($this.hasClass(activeCls)){
					$activeTab = $this;
				}
			});

			this.$tabList = $tabList;

			//默认显示
			if(options.autoActiveAble){
				var $activeTab = $activeTab || 0;
				this.active($activeTab, true);
			}
		},

		//选中
		active : function($activeTab, forceAble, $tabList){
			var options = this.getOptions(),
				activeCls = options.activeCls,
				isActive = false;
			$tabList = $tabList || this.$tabList;

			//允许索引
			if(typeof $activeTab === 'number'){
				$activeTab = $tabList.eq($activeTab);
			}
			isActive = $activeTab.hasClass(activeCls);

			//全部取消选中
			$tabList.each(function(){
				var href = $(this).removeClass(activeCls).attr(options.href);

				//效果css
				var $panel = $(href);
				$panel.removeClass(activeCls).removeClass(options.animateInCls);
			});

			//选中状态下则取消选中
			if(!(options.unActiveAble && isActive) || forceAble){
				//选中
				$activeTab.addClass(activeCls);
				var $activePanel = $($activeTab.attr(options.href)).addClass(activeCls),
					tabUrl = $activeTab.attr(options.url);

				//效果css
				setTimeout(function(){
					$activePanel.addClass(options.animateInCls);
				}, 20);

				//远程加载
				if(tabUrl){
					ajaxer.ajax({
						url : tabUrl,
						dataType : 'text',
						success : function(html){
							$activePanel.html(html);
						}
					});
					if(options.cacheAble){
						$activeTab.removeAttr(options.url);
					}
				}
			}

			if(typeof options.onActive === 'function'){
				options.onActive.call(this, $activeTab, $activePanel);
			}
		}
	});

	Taber.defaults = {
		tabCls : 'tab',
		activeCls : 'active',
		animateInCls : 'in',
		href : 'data-tab-href',
		url : 'data-tab-url',
		//自动选中
		autoActiveAble : true,
		//是否支持取消选中
		unActiveAble : true,
		//链接地址是否缓存
		cacheAble : true,
		//选中事件
		onActive : null
	};

	return tabs;

});